<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>首页 - 商家信息</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-100 flex flex-col items-center justify-center h-screen p-4">

<!-- 商家信息展示 -->
<div id="merchantTableContainer" class="w-full max-w-6xl bg-white p-6 rounded shadow-md">
    <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold">住哪儿订房</h2>
        <div class="space-x-4">

            <!-- 登录注册按钮 -->
            <button id="authButton" class="bg-purple-500 text-white px-3 py-1 rounded">登录/注册</button>

            <!-- 刷新按钮 -->
            <button id="refreshButton" class="bg-blue-600 text-white px-3 py-1 rounded">刷新</button>

            <!-- 返回默认页面按钮 -->
            <button id="backToDefault" class="bg-blue-500 text-white px-3 py-1 rounded">返回默认</button>

            <!-- 搜索框 -->
            <input id="searchKeyword" type="text" placeholder="输入关键词" class="border p-1 rounded" />

            <!-- 搜索类型 -->
            <select id="searchType" class="border p-1 rounded">
                <option value="">全部搜索</option>
                <option value="name">按名称搜索</option>
                <option value="keyword">按关键字搜索</option>
            </select>

            <!-- 排序字段 -->
            <select id="sortField" class="border p-1 rounded">
                <option value="establishmentYear">按建立年份</option>
                <option value="salesVolume">按销量</option>
            </select>

            <!-- 排序方式 -->
            <select id="sortOrder" class="border p-1 rounded">
                <option value="asc">升序</option>
                <option value="desc">降序</option>
            </select>

            <!-- 搜索按钮 -->
            <button id="searchButton" class="bg-green-500 text-white px-3 py-1 rounded">搜索</button>
            <!-- 重置按钮 -->
            <button id="resetButton" class="bg-gray-500 text-white px-3 py-1 rounded">重置</button>
        </div>
    </div>

    <!-- 表格内容 -->
    <div id="merchantContent">
        <p class="text-gray-500">正在加载商家信息...</p>
    </div>

    <!-- 分页控件 -->
    <div id="pagination" class="flex justify-center mt-4 space-x-2"></div>
</div>

<script>
    let merchantsData = [];
    let currentPage = 1;
    let pageSize = 5; // 每页显示 5 个商家

    function getRefreshedUrl(url) {
    const timestamp = new Date().getTime();
    return url + (url.includes('?') ? '&' : '?') + 't=' + timestamp;
    }

    async function loadApprovedMerchants(
  keyword = '',
  searchType = '', // 区分搜索类型
  sortField = 'establishmentYear',
  sortOrder = 'asc',
  pageNumber = 1,
  pageSize = 5
) {
  try {
    let url = '/approved-merchants';
    const params = {
      keyword,
      searchType,
      sortField,
      sortOrder,
      pageNumber,
      pageSize
    };
    const queryString = new URLSearchParams(params).toString();
    url += '?' + queryString;

    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);

    const data = await response.json();

    const container = document.getElementById('merchantContent');
    if (data.data.length === 0) {
      container.innerHTML = '<p class="text-center text-gray-500">暂无符合条件的商家</p>';
      return;
    }

    let html = `
      <table class="min-w-full table-auto border-collapse">
        <thead>
          <tr class="bg-gray-100 text-left">
            <th class="py-2 px-4 border-b">商家名称</th>
            <th class="py-2 px-4 border-b">地址</th>
            <th class="py-2 px-4 border-b">建立年份</th>
            <th class="py-2 px-4 border-b">联系方式</th>
            <th class="py-2 px-4 border-b">关键字</th>
            <th class="py-2 px-4 border-b">营业状态</th>
            <th class="py-2 px-4 border-b">销量</th>
            <th class="py-2 px-4 border-b">收藏量</th>
          </tr>
        </thead>
        <tbody>`;

    data.data.forEach(m => {
      html += `
        <tr class="hover:bg-gray-50">
          <td class="py-2 px-4 border-b">${m.merchantName}</td>
          <td class="py-2 px-4 border-b">${m.address || '-'}</td>
          <td class="py-2 px-4 border-b">${m.establishmentYear || '-'}</td>
          <td class="py-2 px-4 border-b">${m.contactInfo}</td>
          <td class="py-2 px-4 border-b">${m.keywords}</td>
          <td class="py-2 px-4 border-b">${m.businessStatus}</td>
          <td class="py-2 px-4 border-b">${m.salesVolume || '-'}</td>
          <td class="py-2 px-4 border-b">${m.favoritesCount || '-'}</td>
        </tr>`;
    });

    html += '</tbody></table>';
    container.innerHTML = html;

    updatePagination(data.totalItems, data.currentPage || pageNumber, data.pageSize || pageSize);

  } catch (error) {
    console.error('加载商家信息失败:', error);
    document.getElementById('merchantContent').innerHTML =
      `<p class="text-red-500">错误: ${error.message}</p>`;
  }
}

function updatePagination(totalItems, currentPage, pageSize) {
    const totalPages = Math.ceil(totalItems / pageSize); // 定义 totalPages

    const paginationContainer = document.getElementById('pagination');
    paginationContainer.innerHTML = '';

    if (totalPages <= 1) return;

    for (let i = 1; i <= totalPages; i++) {
        const button = document.createElement('button');
        button.textContent = `第${i}页`;
        button.className = 'mx-1 px-2 py-1 bg-gray-200 rounded hover:bg-gray-300';
        if (i === currentPage) {
            button.classList.add('bg-blue-500', 'text-white');
        }

        button.addEventListener('click', () => {
            const keyword = document.getElementById('searchKeyword').value;
            const searchType = document.getElementById('searchType').value;
            const sortField = document.getElementById('sortField').value;
            const sortOrder = document.getElementById('sortOrder').value;
            loadApprovedMerchants(keyword, searchType, sortField, sortOrder, i, pageSize);
        });

        paginationContainer.appendChild(button);
    }

    const gotoInput = document.createElement('input');
    gotoInput.type = 'number';
    gotoInput.placeholder = '页码';
    gotoInput.className = 'border p-1 rounded';

    const gotoButton = document.createElement('button');
    gotoButton.textContent = '跳转';
    gotoButton.className = 'bg-green-500 text-white px-2 py-1 rounded ml-2';

    gotoButton.onclick = () => {
        const page = parseInt(gotoInput.value);
        if (page >= 1 && page <= totalPages) {
            const keyword = document.getElementById('searchKeyword').value;
            const searchType = document.getElementById('searchType').value;
            const sortField = document.getElementById('sortField').value;
            const sortOrder = document.getElementById('sortOrder').value;
            loadApprovedMerchants(keyword, searchType, sortField, sortOrder, page, pageSize);
        } else {
            alert('请输入有效页码');
        }
    };

    paginationContainer.appendChild(gotoInput);
    paginationContainer.appendChild(gotoButton);

    // 显示当前页码
    const currentPageDisplay = document.createElement('span');
    currentPageDisplay.textContent = ` 当前页码: ${currentPage} / ${totalPages}`; // 正确引用 totalPages
    currentPageDisplay.classList.add('ml-2', 'text-gray-600');

    paginationContainer.appendChild(currentPageDisplay);
}



    // 绑定搜索事件
    document.getElementById('searchButton').addEventListener('click', () => {
      const keyword = document.getElementById('searchKeyword').value;
      const searchType = document.getElementById('searchType').value;
      const sortField = document.getElementById('sortField').value;
      const sortOrder = document.getElementById('sortOrder').value;
      loadApprovedMerchants(keyword, searchType, sortField, sortOrder, 1, pageSize);
    });

    // 绑定重置事件
    document.getElementById('resetButton').addEventListener('click', () => {
      document.getElementById('searchKeyword').value = '';
      document.getElementById('searchType').value = '';
      document.getElementById('sortField').value = 'establishmentYear';
      document.getElementById('sortOrder').value = 'asc';
      currentPage = 1;
      loadApprovedMerchants('', '', 'establishmentYear', 'asc', 1, pageSize);
    });

    // 绑定返回默认页面事件
document.getElementById('backToDefault').addEventListener('click', () => {
    document.getElementById('searchKeyword').value = '';
    document.getElementById('searchType').value = '';
    document.getElementById('sortField').value = 'establishmentYear';
    document.getElementById('sortOrder').value = 'asc';
    currentPage = 1;
    loadApprovedMerchants('', '', 'establishmentYear', 'asc', 1, pageSize);
});

// 绑定登录注册按钮事件
document.getElementById('authButton').addEventListener('click', () => {
    window.location.href = 'auth.html';
});

//绑定刷新事件
document.getElementById('refreshButton').addEventListener('click', () => {
    const keyword = document.getElementById('searchKeyword').value;
    const searchType = document.getElementById('searchType').value;
    const sortField = document.getElementById('sortField').value;
    const sortOrder = document.getElementById('sortOrder').value;
    // 显示刷新提示
    showRefreshNotification();

    loadApprovedMerchants(keyword, searchType, sortField, sortOrder, currentPage, pageSize);
});

// 添加刷新提示函数
function showRefreshNotification() {
    const notification = document.createElement('div');
    notification.textContent = '🔄 正在刷新...';
    notification.id = 'refreshNotification';
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.backgroundColor = '#4CAF50';
    notification.style.color = 'white';
    notification.style.padding = '10px 20px';
    notification.style.borderRadius = '8px';
    notification.style.zIndex = '1000';
    notification.style.transition = 'opacity 0.5s ease-out';

    document.body.appendChild(notification);

    // 切换文本并淡出
    setTimeout(() => {
        notification.textContent = '✅ 刷新成功！';
    }, 300);

    setTimeout(() => {
        notification.style.opacity = '0';
    }, 1500);

    setTimeout(() => {
        document.body.removeChild(notification);
    }, 2000);
}

    // 页面加载时默认请求
    window.onload = () => {
      loadApprovedMerchants();
    };
</script>

</body>
</html>

